package com.ruoyi.system.controller;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.commons.utils.Constants;
import com.ruoyi.system.commons.utils.IdGeneratorSnowflake;
import com.ruoyi.system.domain.QaDetailModel;
import com.ruoyi.system.domain.dto.*;
import com.ruoyi.system.service.OneMapFwService;
import com.ruoyi.system.service.PromptService;
import com.ruoyi.system.service.QaDetailService;
import org.apache.commons.text.StringSubstitutor;

import org.junit.jupiter.api.Test;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther Yulong Liu
 * @Date 2023/12/12 14:33
 * @Description 知识库问答接口
 **/

@RestController
@RequestMapping("/qa")
public class QaDetailController {
    @Autowired
    private QaDetailService qaDetailService;

    @Autowired
    private OneMapFwService oneMapFwService;

    @Autowired
    private PromptService promptService;


    @PostMapping("/multibase_chat")
    public R<MultibaseAnswerDto> multibase_chat(@RequestBody MultibaseQueryDto multibaseQueryDto) {
        /**@Description: 拿到前台的请求，向大模型发送请求，并存入数据库，最后返回给前台展示
         * @param [multibaseQueryDto]
         * @return R<MultibaseAnswerDto>
         */
        System.out.println("+++++++++++++++++session_id+++++++++++++++++++++++++++++++");
        System.out.println(multibaseQueryDto.getSessionId());
        System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");

        //如果没给session_id则证明是新的对话
        if (multibaseQueryDto.getSessionId() == null){
            //雪花算法生成一个session_id
            IdGeneratorSnowflake idGenerator = new IdGeneratorSnowflake();
            Long sessionId = idGenerator.snowflakeId();
            multibaseQueryDto.setSessionId(sessionId.toString());
        }

        MultibaseAnswerDto multibaseAnswerDto = qaDetailService.HandleMultibaseAnswers(multibaseQueryDto);

        if (multibaseAnswerDto.getAnswer() == null){
            return R.fail("回答失败");
        }else {
            return R.ok(multibaseAnswerDto);
        }
    }

    @PostMapping("/list_session")
    public R<List<HistoryBriefDto>> listBriefHistory(){
        /**@Description:检索找到用户对应session下的所有的记录
         * @return R<List<HistoryBriefDto>>
         */
        List<HistoryBriefDto> historyBriefDtoList = qaDetailService.listDetailByUserId(SecurityUtils.getUserId());
        if (historyBriefDtoList == null){
            return R.fail("该用户没有对应历史记录");
        }else {
            return R.ok(historyBriefDtoList);
        }
    }

    @PostMapping("/logic_delete_session")
    public R deleteBySession(@RequestBody SessionIdDto sessionIdDto){
        /**@Description: 逻辑删除
         * @param [sessionIdDto]
         * @return R
         */
        if (sessionIdDto.getSession_id() == null){
            return R.fail("必须提供会话id");
        }
        //找到用户对应session下的所有记录，给他们的 修改时间 赋值为当前 和 isdeleted 赋值为1
        LambdaUpdateWrapper<QaDetailModel> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(QaDetailModel::getIsDeleted,1).eq(QaDetailModel::getSessionId, sessionIdDto.getLongSessionId());
        boolean res = qaDetailService.update(updateWrapper);
        if (res){
            return R.ok(null,"删除成功！");
        }else {
            return R.fail("删除失败！");
        }
    }

    @PostMapping("/session_details")
    public R<List<SessionHistoryDto>> listDetailBySession(@RequestBody SessionIdDto sessionIdDto){
        /**@Description: 找到用户对应session下的所有记录，按照时间降序组织好数据
         * @param [sessionIdDto]
         * @return R<List<SessionHistoryDto>>
         */
        if (sessionIdDto.getSession_id() == null){
            return R.fail("必须提供会话id");
        }
        List<SessionHistoryDto> resultsList = qaDetailService.listSessionDetail(sessionIdDto.getLongSessionId());

        if (resultsList == null){
            return R.fail("此session没有数据");
        }else {
            return R.ok(resultsList);
        }
    }


    @PostMapping("/main")
    public R query(@RequestBody QADto dto){

        MultibaseQueryDto multibaseQueryDto = new MultibaseQueryDto();
        BeanUtils.copyProperties(dto,multibaseQueryDto);
        System.out.println("+++++++++++++++++session_id+++++++++++++++++++++++++++++++");
        System.out.println(multibaseQueryDto.getSessionId());
        System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");

        //如果没给session_id则证明是新的对话
        if (multibaseQueryDto.getSessionId() == null){
            //雪花算法生成一个session_id
            IdGeneratorSnowflake idGenerator = new IdGeneratorSnowflake();
            Long sessionId = idGenerator.snowflakeId();
            multibaseQueryDto.setSessionId(sessionId.toString());
        }

        Object res = qaDetailService.mainLogic(multibaseQueryDto);
        System.out.println(res);
        return  R.ok(res);

    }

    @PostMapping("/oneMapFw")
    public R query(@RequestBody String query){

        String res = oneMapFwService.getDismantledQuery(query);
        System.out.println(res);
        return  R.ok(res);

    }

    @PostMapping("/mark_zhishui")
    public R markZhiShui(@RequestBody MarkDto markDto){
        if (markDto.getSessionId()== null || markDto.getGmtModified()== null){
            R.fail("评分失败！");
        }
        boolean res = qaDetailService.markByHuman(markDto);
        if (res){
            return R.ok("评分成功！");
        }else {
            return R.fail("评分失败！");
        }
    }
}
